package cn.edu.stu.syllabus.oa.detail;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Picture;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.edu.stu.syllabus.R;
import cn.edu.stu.syllabus.adapters.OaFileAdapter;
import cn.edu.stu.syllabus.base.BaseFragment;
import cn.edu.stu.syllabus.base.StoreProxy;
import cn.edu.stu.syllabus.repository.oaFile.local.OaFileEntry;
import cn.edu.stu.syllabus.utils.FunctionCaller;
import cn.edu.stu.syllabus.utils.SaveBitmap2FileUtils;
import cn.edu.stu.syllabus.utils.ToastUtils;
import cn.edu.stu.syllabus.widgets.DividerItemDecoration;
import cn.edu.stu.syllabus.widgets.MyItemAnimator;
import cn.edu.stu.syllabus.widgets.NestedScrollViewScrollAdapter;
import cn.edu.stu.syllabus.widgets.NoHorNestedScrollView;
import cn.edu.stu.syllabus.widgets.SnackbarUtil;

import static cn.edu.stu.syllabus.utils.NullPointerUtils.checkNotNull;

/**
 * Created by daidaijie on 2017/3/18.
 */

public class OaDetailFragment extends BaseFragment implements OaDetailContract.View, OaDetailActivity.OnStarButtonStateChangeListener, OaDetailActivity.OnScreenshotClickListener {

    OaDetailContract.Presenter mPresenter;

    OaFileAdapter mOaFileAdapter;

    @BindView(R.id.oaFileRecyclerView)
    RecyclerView mOaFileRecyclerView;
    @BindView(R.id.oADetailWebView)
    WebView mOADetailWebView;
    @BindView(R.id.oADetailLinearLayout)
    LinearLayout mOADetailLinearLayout;
    @BindView(R.id.oADetailRootLayout)
    NoHorNestedScrollView mOADetailRootLayout;

    private View mErrorView;

    private View mEmptyView;

    View mOaFilesHeadView;

    private boolean mIsContentShow;

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_oa_detail;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        mOaFilesHeadView = LayoutInflater.from(mActivity).inflate(R.layout.header_oa_file,
                (ViewGroup) mOaFileRecyclerView.getParent(), false);

        Drawable decLineDrawable = ContextCompat.getDrawable(mActivity, R.drawable.dev_line);
        DividerItemDecoration itemDecoration = new DividerItemDecoration(
                mActivity, DividerItemDecoration.VERTICAL_LIST, decLineDrawable);
        itemDecoration.setHeight(1);
        mOaFileRecyclerView.addItemDecoration(itemDecoration);
        mOaFileRecyclerView.setItemAnimator(new MyItemAnimator());
        mOaFileRecyclerView.setNestedScrollingEnabled(false);

        mOaFileAdapter = new OaFileAdapter(new ArrayList<OaFileEntry>());
        mOaFileRecyclerView.setLayoutManager(new LinearLayoutManager(mActivity));

        mOaFileRecyclerView.setAdapter(mOaFileAdapter);

        mIsContentShow = false;

        initWebView();

        mEmptyView = LayoutInflater.from(mActivity).inflate(R.layout.empty_oa_file
                , (ViewGroup) mOaFileRecyclerView.getParent(), false);

        mErrorView = LayoutInflater.from(mActivity).inflate(R.layout.error_oa_file
                , (ViewGroup) mOaFileRecyclerView.getParent(), false);

        TextView errorTextView = (TextView) mErrorView.findViewById(R.id.errTextView);
        errorTextView.setText("加载失败，请点击重试");
        mErrorView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPresenter.loadOaFiles();
            }
        });

        mOADetailRootLayout.setOnScrollChangeListener(new NestedScrollViewScrollAdapter() {
            @Override
            public void onScrollToBottom() {
                mOADetailRootLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        showAppBar();
                    }
                }, 50);
            }
        });

        StoreProxy.onRestoreInstanceState(savedInstanceState, mPresenter);
        mPresenter.subscribe();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        StoreProxy.onSaveInstanceState(outState, mPresenter);
    }

    private void initWebView() {
        WebSettings webSettings = mOADetailWebView.getSettings();
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setDefaultFontSize(16);

        mOADetailWebView.setDrawingCacheEnabled(true);

        mOADetailWebView.setWebViewClient(new WebViewClient() {
            public void onPageFinished(WebView view, String url) {
                ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(mOADetailLinearLayout, "alpha", 0.0f, 1.0f);
                objectAnimator.setDuration(300);
                objectAnimator.setInterpolator(new AccelerateInterpolator());
                objectAnimator.start();
                objectAnimator.addListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        super.onAnimationEnd(animation);
                        mIsContentShow = true;
                    }
                });
            }
        });
    }

    @Override
    public void setPresenter(OaDetailContract.Presenter presenter) {
        mPresenter = checkNotNull(presenter);
    }

    @Override
    public void setOaFilesHeader(boolean isShow) {
        mOaFileAdapter.removeAllHeaderView();
        if (isShow) {
            mOaFileAdapter.addHeaderView(mOaFilesHeadView);
        }
    }

    @Override
    public void showOaInfoContent(String content) {
        mOADetailWebView.loadData(content, "text/html; charset=UTF-8", null);
    }

    @Override
    public void showOaFiles(List<OaFileEntry> oaFileEntries) {
        mOaFileAdapter.setNewData(oaFileEntries);
    }

    @Override
    public void showLoadingError() {
        mOaFileAdapter.setEmptyView(mErrorView);
    }

    @Override
    public void showLoading() {
        mOaFileAdapter.setEmptyView(mEmptyView);
    }

    @Override
    public void onDestroyView() {
        mPresenter.unsubscribe();
        super.onDestroyView();
    }

    @Override
    public boolean isStar() {
        return mPresenter.isStarOaInfo();
    }

    @Override
    public void onStateChange(boolean isStar) {
        if (isStar) {
            mPresenter.starOaInfo();
        } else {
            mPresenter.unstarOaInfo();
        }
    }

    private Bitmap getWebViewBitmap() throws OutOfMemoryError {
        Picture picture = mOADetailWebView.capturePicture();
        Bitmap screenShoot = Bitmap.createBitmap(picture.getWidth(),
                picture.getHeight(), Bitmap.Config.ARGB_4444);
        Canvas c = new Canvas(screenShoot);
        picture.draw(c);
        return screenShoot;
    }

    @Override
    public void onScreenshotClick() {
        if (!mIsContentShow) {
            ToastUtils.getInstance().showToast(ToastUtils.ToastType.WARNING, "未加载完成", Snackbar.LENGTH_SHORT);
            return;
        }

        Bitmap screenShoot;
        try {
            screenShoot = getWebViewBitmap();
        } catch (OutOfMemoryError err) {
            showScreenshotFail("图片太大，无法进行截取");
            return;
        }

        SaveBitmap2FileUtils.saveBitmap2File(mActivity, screenShoot, System.currentTimeMillis() + ".jpg"
                , 75, new SaveBitmap2FileUtils.OnSaveFileCallBack() {
                    @Override
                    public void onSuccess(File file) {
                        showScreenSuccess(file);
                    }

                    @Override
                    public void onFail(String msg) {
                        showScreenshotFail(msg);
                    }
                });
    }

    private void showScreenSuccess(final File file) {
        SnackbarUtil.LongSnackbar(mOADetailWebView, "截图成功", SnackbarUtil.getNormalTextColor(),
                SnackbarUtil.getNormalBackgroundColor())
                .setAction("打开图片", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        FunctionCaller.openGallery(mActivity, file);
                    }
                }).setActionTextColor(SnackbarUtil.getActionGreen()).show();
    }

    private void showScreenshotFail(String msg) {
        SnackbarUtil.ShortSnackbar(mOADetailWebView, msg, SnackbarUtil.Alert).show();
    }
}
